<?php


namespace App\PubApi\Controller;

use App\Facades\JWTAuth;
use EchoPHP\Facades\Request;

/**
 * 控制器核心基类，提供基本信息等
 * Class BaseController
 * @package App\Service
 */
abstract class BaseController {

    /**
     * 权限校验
     * @var array
     */
    protected $rightCheck = [];

    protected $request;
    private $currentController;
    private $currentAction;

    public function __construct() {
        $this->request = Request::instance();
        $this->currentController = $this->request->getAttribute('controller');
        $this->currentAction = $this->request->getAttribute('action');
        //权限点键名全部改成小写，防止权限失效
        $this->rightCheck = array_change_key_case($this->rightCheck, CASE_LOWER);
    }

    /**
     * 获取当前控制器
     * @return array|mixed|void|null
     */
    public function getCurrentController() {
        return $this->currentController;
    }

    /**
     * 获取当前操作名
     * @return array|mixed|void|null
     */
    public function getCurrentAction() {
        return strtolower($this->currentAction);
    }

    /**
     * 输出json响应
     * @param array $responseData
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function json(array $responseData) {
        return response()->json($responseData);
    }


    /**
     * 控制器预处理
     * @param $method
     * @param $parameters
     * @return mixed
     */
    public function callAction($method, $parameters) {
        $method = strtolower($method);
        if (isset($this->rightCheck[$method])) {
            UserAuth::chkRight($this->rightCheck[$method]);
        }
        return $this->{$method}(...$parameters);
    }

    /**
     * 获取小程序登录信息
     * @param \EchoPHP\Http\Request $request
     * @return array
     */
    protected function getXcxLoginInfo() {
        $authToken = $this->request->getParam('xcxToken', '');
        try {
            $loginInfo = JWTAuth::decode($authToken);
        } catch (\Exception $e) {
            $loginInfo = [];
        }
        return $loginInfo;
    }
}